/**
 *  Welcome to your gulpfile!
 *  The gulp tasks are splitted in several files in the gulp directory
 *  because putting all here was really too long
 */

'use strict';

var gulp = require('gulp');
var debug = require('gulp-debug');
var path = require('path');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var del = require('del');
var webserver = require('gulp-webserver');
var sass = require('gulp-sass');
var foreach = require('gulp-foreach');
var cssmin = require('gulp-cssmin');
var addsrc = require('gulp-add-src');
var replace = require('gulp-replace');
var shell = require('gulp-shell');
var fs = require('fs');
var sourcemaps = require('gulp-sourcemaps');

/**
 * 把coffee 转换成 js 并合并压缩
 * 把html压缩
 *
 */
gulp.task('default', ['html', 'coffee', 'sass', 'concat-vendor'], function(){

	// record last commit in window.CloudReading.version
	var data = fs.readFileSync('version.txt');
	//var versionData = "window.CloudReading.lastCommit";
	//var isSetCloudReading ="if(!window.CloudReading){" +
	//						"window.CloudReading={};"+
	//						"}\n";
	////console.log(isSetCloudReading )
	//var appendData = versionData+'='+"'"+data.toString().trim()+"'"+';\n'; // 末尾必须加 ; 不然压缩会有问题
	var appendData = 'console.info(' + "'"+data.toString().trim() + "'" +');\n'; // 末尾必须加 ; 不然压缩会有问题
	console.log(appendData);
	fs.appendFileSync('.tmp/main-controller.js',appendData);

	gulp.src('.tmp/**/*.js')
		.pipe(sourcemaps.init())
        .pipe(concat('cmis-directive.min.js'))
        .pipe(uglify({mangle: false}))
		//.pipe($.sourcemaps.write())
		//.pipe(sourcemaps.write('maps'))
        .pipe(gulp.dest('dist'));

	//return gulp.src(['dist/cmis-vendor.min.js', 'dist/cmis-directive.min.js'])
	//	.pipe(concat('cmis-directive-all.min.js'))
	//	.pipe(uglify({mangle: false}))
	//	.pipe(gulp.dest('dist'))
});

gulp.task('shell', shell.task([
	'git describe --always > version.txt'
]));

gulp.task('concat-vendor', function(){
	gulp.src([
		'bower_components/base64/base64.min.js',
		'bower_components/superagent/superagent.js',
		'bower_components/smx-cmis/lib/cmis.js',
		'bower_components/angular/angular.js',
		'bower_components/FileSaver/dist/FileSaver.js',
		'bower_components/angular-local-storage/dist/angular-local-storage.min.js',
		'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
		'bower_components/angular-translate/angular-translate.js',
		'bower_components/angular-toastr/dist/angular-toastr.tpls.js',
		'lib/ng-context-menu.js',
		'lib/hover-menu.js',
		'bower_components/angular-file-model/angular-file-model.js',
		'bower_components/clipboard/dist/clipboard.js',
		'bower_components/ngclipboard/dist/ngclipboard.js',
		'bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
		'bower_components/angular-animate/angular-animate.js',
		'bower_components/jquery-qrcode/jquery.qrcode.min.js',
	])
		.pipe(sourcemaps.init())
		.pipe(concat('cmis-vendor.min.js'))
		.pipe(uglify({mangle: false}))
		//.pipe($.sourcemaps.write())
		//.pipe(sourcemaps.write('maps'))
		.pipe(gulp.dest('dist'))
});

var errorHandler = function(title) {
    'use strict';

    return function(err) {
        //gutil.log(gutil.colors.red('[' + title + ']'), err.toString());
        this.emit('end');
    };
};

var $ = require('gulp-load-plugins')();

gulp.task('coffee',['clean','shell'], function () {
	//gulp.src('version.txt')
	//	.pipe(gulp.dest('.tmp'));
    return gulp.src('src/**/*.coffee')
        .pipe($.sourcemaps.init())
        .pipe($.coffeelint())
        //.pipe($.coffeelint.reporter())
        .pipe($.coffee()).on('error', errorHandler('CoffeeScript'))
        //.pipe($.sourcemaps.write())
        .pipe(gulp.dest('.tmp'))
        .pipe($.size())
});

gulp.task('serve-prepare', function () {
    gulp.src('src/**/*.coffee')
        .pipe($.coffeelint())
        .pipe($.coffeelint.reporter())
        .pipe($.coffee()).on('error', errorHandler('CoffeeScript'))
        .pipe(gulp.dest('src'));
	gulp.src('tests/**/*.coffee')
		.pipe($.coffeelint())
		.pipe($.coffeelint.reporter())
		.pipe($.coffee()).on('error', errorHandler('CoffeeScript'))
		.pipe(gulp.dest('tests'));
    gulp.src('src/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('src'));
});

gulp.task('html', function(){
    return gulp.src('src/template-path/*.html')
        .pipe($.minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe($.angularTemplatecache('templateCacheHtml.js', {
            module: 'UCX.Cmis',
            root: 'template-path'
        }))
        .pipe(gulp.dest('.tmp/'))
});
gulp.task('clean', function () {
    return del.sync(['dist', '.tmp']);
});

//  share plugin need start
gulp.task('default-share', ['html-for-share-plugin', 'coffee', 'sass', 'concat-vendor-for-share'], function(){

	var data = fs.readFileSync('version.txt');
	var appendData = 'console.info(' + "'"+data.toString().trim() + "'" +');\n'; // 末尾必须加 ; 不然压缩会有问题
	console.log(appendData);
	fs.appendFileSync('.tmp/main-controller.js',appendData);

	gulp.src([
			'.tmp/directives/cloud-reading-share.js',
			'.tmp/directives/common.js',
			'.tmp/language/*.js',
			'.tmp/cmis-directive.js',
			'.tmp/modal-controller.js',
			'.tmp/models.js',
			'.tmp/service.js',
			'.tmp/share/templateCacheHtml.js'
		])
		.pipe(sourcemaps.init())
		.pipe(concat('cmis-directive-for-share.min.js'))
		.pipe(uglify({mangle: false}))
		//.pipe($.sourcemaps.write())
		//.pipe(sourcemaps.write('maps'))
		.pipe(gulp.dest('dist'));
});
gulp.task('html-for-share-plugin', function(){
	return gulp.src([
			'src/template-path/confirm.html',
			'src/template-path/new-share.html'
		]
	)
		.pipe($.minifyHtml({
			empty: true,
			spare: true,
			quotes: true
		}))
		.pipe($.angularTemplatecache('templateCacheHtmlForSharePlugin.js', {
			module: 'UCX.Cmis',
			root: 'template-path'
		}))
		.pipe(gulp.dest('.tmp/share'))
});
gulp.task('concat-vendor-for-share', function(){
	gulp.src([
			'bower_components/base64/base64.min.js',
			'bower_components/superagent/superagent.js',
			'bower_components/smx-cmis/lib/cmis.js',
			'bower_components/angular/angular.js',
			'bower_components/angular-local-storage/dist/angular-local-storage.min.js',
			'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
			'bower_components/angular-translate/angular-translate.js',
			'bower_components/angular-toastr/dist/angular-toastr.tpls.js',
			'bower_components/clipboard/dist/clipboard.js',
			'bower_components/ngclipboard/dist/ngclipboard.js',
			'bower_components/jquery-qrcode/jquery.qrcode.min.js',
		])
		.pipe(sourcemaps.init())
		.pipe(concat('cmis-vendor-for-share.min.js'))
		.pipe(uglify({mangle: false}))
		//.pipe($.sourcemaps.write())
		//.pipe(sourcemaps.write('maps'))
		.pipe(gulp.dest('dist'))
});
//  share plugin need end

//  gulp webpack start
var webpack = require('webpack-stream');
gulp.task('webpack', function() {
	return gulp.src([
			'node_modules/jquery/dist/jquery.js',
			'node_modules/base-64/base64.js',
			'bower_components/superagent/lib/client.js',
			//'node_modules/cmis/lib/cmis.js',
			'node_modules/angular/angular.js',
			'node_modules/FileSaver/FileSaver.min.js',
			'node_modules/angular-local-storage/dist/angular-local-storage.js',
			'node_modules/angular-bootstrap/ui-bootstrap-tpls.js',
			'node_modules/angular-translate/dist/angular-translate.js',
			'node_modules/angular-toastr/dist/angular-toastr.tpls.js',
			'lib/ng-context-menu.js',
			'lib/hover-menu.js',
			'node_modules/angular-file-model/angular-file-model.js',
			'node_modules/clipboard/dist/clipboard.js',
			'bower_components/ngclipboard/dist/ngclipboard.js',
			'bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
			'node_modules/angular-animate/angular-animate.js',
			'node_modules/jquery-qrcode/jquery.qrcode.min.js',
	])
		.pipe(webpack())
		.pipe(concat('cmis-vendor.js'))
		.pipe(gulp.dest('dist/'));
});


//  gulp webpack end



gulp.task('sass', function () {
	gulp.src('src/theme/**/*.scss')
		.pipe(foreach(function(stream, file){
			gulp.src(file.path)
				.pipe(addsrc(['src/style/*.scss']))
				.pipe(sass().on('error', sass.logError))
				.pipe(addsrc(
					[
						'bower_components/angular-toastr/dist/angular-toastr.css',
						'bower_components/animate.css/animate.min.css'
					]
				))
				.pipe(concat('style.' + path.basename(file.path, '.scss') + '.min.css'))
				.pipe(cssmin())
				.pipe(gulp.dest('dist'));
			return stream;
		}));
});

gulp.task('serve', ['serve-prepare'], function() {
    gulp.src('demo')
        .pipe(webserver({
            livereload: false,
            open: true,
            path: '/',
            fallback: 'index.html',
			port:9999,
			host:'0.0.0.0'
        }));
});

gulp.task('watch',function () {
	gulp.watch('src/template-path/*.html', ['cptemplatepath']);
	gulp.watch('src/**/*.coffee', ['cpsrcpath']);
	gulp.watch('src/style/*.scss', ['cpsrcpath']);
});

gulp.task('coffeetojs',function(){
	return gulp.src('src/**/*.coffee')
		.pipe($.sourcemaps.init())
		.pipe($.coffeelint())
		//.pipe($.coffeelint.reporter())
		.pipe($.coffee()).on('error', errorHandler('CoffeeScript'))
		//.pipe($.sourcemaps.write())
		.pipe(gulp.dest('src'))
		.pipe($.size())
});
gulp.task('scsstocss',function(){
	return gulp.src('src/**/*.scss')
		.pipe(sass().on('error', sass.logError))
		.pipe(gulp.dest('src'))
		.pipe($.size())
});

gulp.task('cptemplatepath',function(){
	var targetBasePath =  process.argv[4];
	console.log('target path: '+targetBasePath);
	return gulp.src('src/template-path/*')
		.pipe(gulp.dest(process.argv[4]))
});
gulp.task('cpsrcpath',['scsstocss','coffeetojs'],function(){
	var targetBasePath =  process.argv[6];
	console.log('target path: '+targetBasePath);
	return gulp.src('src/**/*')
		.pipe(gulp.dest(process.argv[6]))
});

gulp.task('cpcmis',['watch'],function() {
	// gulp cpcmis --templatePath your_path --srcPath your_src_path
	// 我的 是这样配置的
	// gulp cpcmis --path /Users/wangwei/docomobile/cloudReadingHD/www/template-path --path2 /Users/wangwei/docomobile/cloudReadingHD/www/lib/cmis-angularjs-directive/src
	if(!process.argv[4]){
		// 检测路径是否 存在
		console.log('we');

	}
	//console.log(process.argv[4]);
	console.log('it is done');
	// 首先 compile复制一份css和js 过去 然后如果有改动
});

